package control;

import model.Passenger;
import model.Plane;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

public class PassengerController {
    /*
        This method is created to query passenger by booking number
        @ param bookNumber
        @ return Passenger
     */
    Passenger passenger = new Passenger();
    public Passenger queryByBookNumber(String bookNumber){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/data/data.csv"), "utf-8"));//GBK
            String line = null;
            while((line=reader.readLine())!=null){
                String[] item;
                item = line.split(",");
                String bkNum = item[0];
                int count = 0;
                if(bookNumber.equals(bkNum)){
                    passenger.setBookNumber(item[0]);
                    passenger.setSurname(item[1]);
                    passenger.setID(item[2]);
                    passenger.setIsVIP(item[3]);
                    passenger.setBaggage(item[4]);
                    passenger.setStatus(item[5]);
                    for (int i = 6; i < item.length; i += 4) {
                        passenger.setPlaneNum(count,item[i]);
                        passenger.setRow(count,item[i+1]);
                        passenger.setCol(count,item[i+2]);
                        passenger.setFood(count,item[i+3]);
                        count++;
                    }

                    return passenger;
                }
            }
            System.out.println("未查询到数据！");
            return passenger;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return passenger;
    }

    /*
      This method is created to query passenger by surname and ID number
      @ param surname
      @ param ID
      @ return Passenger
   */
    public Passenger queryBySurnameAndID(String surname, String ID){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/data/data.csv"), "utf-8"));//GBK
            String line = null;
            while((line=reader.readLine())!=null){
                String[] item;
                item = line.split(",");
                String surN = item[1];
                String id = item[2];
                if(surname.equals(surN) && ID.equals(id)){
                    passenger.setBookNumber(item[0]);
                    passenger.setSurname(item[1]);
                    passenger.setID(item[2]);
                    passenger.setIsVIP(item[3]);
                    passenger.setBaggage(item[4]);
                    passenger.setStatus(item[5]);
                    int count = 0;
                    for (int i = 6; i < item.length; i += 4) {
                        passenger.setPlaneNum(count,item[i]);
                        passenger.setRow(count,item[i+1]);
                        passenger.setCol(count,item[i+2]);
                        passenger.setFood(count,item[i+3]);
                        count++;
                    }
                    return passenger;
                }
            }
            System.out.println("未查询到数据！");
            return passenger;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return passenger;
    }

    public ArrayList<Plane> queryPlaneInfo(Passenger passenger){
        ArrayList<Plane> list = new ArrayList<Plane>();
        HashSet<String> planeSet = new HashSet<>(Arrays.asList(passenger.getPlaneNum()));
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/data/planeData.csv"), "utf-8"));//GBK
            String line = null;
            while((line=reader.readLine())!=null){
                String[] item;
                item = line.split(",");
                String number = item[0];
                if(planeSet.contains(number)){
                    Plane plane = new Plane();
                    plane.setNumber(item[0]);
                    plane.setSetupTime(item[1]);
                    plane.setLandTine(item[2]);
                    plane.setSetupTerminal(item[3]);
                    plane.setLandTerminal(item[4]);
                    int count = 0;
                    for (int i = 5; i < 9; i++) {
                        plane.setMeal(count++,item[i]);
                    }
                    list.add(plane);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     This method is created to query all passenger's information
     @ return ArrayList, list of Passenger
  */
    public ArrayList<Passenger> queryAll(){
        ArrayList<Passenger> list = new ArrayList<Passenger>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/data/data.csv"), "utf-8"));//GBK
            String line = null;
            Passenger passenger = new Passenger();
            while((line=reader.readLine())!=null){
                String[] item;
                item = line.split(",");
                passenger = new Passenger();
                passenger.setBookNumber(item[0]);
                passenger.setSurname(item[1]);
                passenger.setID(item[2]);
                passenger.setIsVIP(item[3]);
                passenger.setBaggage(item[4]);
                passenger.setStatus(item[5]);
                int count = 0;
                for (int i = 6; i < item.length; i += 4) {
                    passenger.setPlaneNum(count,item[i]);
                    passenger.setRow(count,item[i+1]);
                    passenger.setCol(count,item[i+2]);
                    passenger.setFood(count++,item[i+3]);
                }
                list.add(passenger);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /*
      This method is created to store the passenger's seat information
      @ param bookNumber
      @ param row
      @ param col
      @ return String, show whether succeed
    */
    public void selectSeat(String bookNumber, String currentPlaneNum, String row, String col){
        ArrayList<Passenger> list = this.queryAll();

        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getBookNumber().equals(bookNumber)){
                for (int j = 0; j < list.get(i).getPlaneNum().length; j++) {
                    if(list.get(i).getPlaneNum()[j].equals(currentPlaneNum)){
                        list.get(i).getCol()[j] = col;
                        list.get(i).getRow()[j] = row;
                    }
                }
                System.out.println(list.get(i));
            }
        }
        // open the file
        File writeFile = new File("src/data/data.csv");
        try{
            BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile));

            for (int i = 0; i < list.size(); i++) {
                // write bytes to stream
                writeText.write(list.get(i).getBookNumber()+","+list.get(i).getSurname()+","+list.get(i).getID()+
                        ","+list.get(i).getIsVIP()+","+list.get(i).getBaggage()+","+list.get(i).getStatus()+","+list.get(i).getPlaneNum()[0]+","+list.get(i).getRow()[0]+","+
                        list.get(i).getCol()[0]+","+list.get(i).getFood()[0]+","+list.get(i).getPlaneNum()[1]+","+
                        list.get(i).getRow()[1]+","+list.get(i).getCol()[1]+","+list.get(i).getFood()[1]+","+
                        list.get(i).getPlaneNum()[2]+","+list.get(i).getRow()[2]+","+list.get(i).getCol()[2]+","+
                        list.get(i).getFood()[2]+","+list.get(i).getPlaneNum()[3]+","+list.get(i).getRow()[3]+","+
                        list.get(i).getCol()[3]+","+list.get(i).getFood()[3]);
                // line feed
                writeText.newLine();
            }
            // Use buffer area
            writeText.flush();
            // close buffer
            writeText.close();
        }catch (FileNotFoundException e){
            System.out.println("没有找到指定文件");
        }catch (IOException e){
            System.out.println("文件读写出错");
        }
    }

    /*
     This method is created to store the passenger's food information
     @ param bookNumber
     @ param food
     @ return String, show whether succeed
   */
    public String selectFood(String bookNumber, String currentPlaneNum, String food){
        ArrayList<Passenger> list = this.queryAll();

        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getBookNumber().equals(bookNumber)){
                for (int j = 0; j < list.get(i).getPlaneNum().length; j++) {
                    if(list.get(i).getPlaneNum()[j].equals(currentPlaneNum)){
                        list.get(i).getFood()[j] = food;
                    }
                }
                System.out.println(list.get(i));
            }
        }
        File writeFile = new File("src/data/data.csv");
        try{
            BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile));
            for (int i = 0; i < list.size(); i++) {
                // write bytes to stream
                writeText.write(list.get(i).getBookNumber()+","+list.get(i).getSurname()+","+list.get(i).getID()+
                        ","+list.get(i).getIsVIP()+","+list.get(i).getBaggage()+","+list.get(i).getStatus()+","+list.get(i).getPlaneNum()[0]+","+list.get(i).getRow()[0]+","+
                        list.get(i).getCol()[0]+","+list.get(i).getFood()[0]+","+list.get(i).getPlaneNum()[1]+","+
                        list.get(i).getRow()[1]+","+list.get(i).getCol()[1]+","+list.get(i).getFood()[1]+","+
                        list.get(i).getPlaneNum()[2]+","+list.get(i).getRow()[2]+","+list.get(i).getCol()[2]+","+
                        list.get(i).getFood()[2]+","+list.get(i).getPlaneNum()[3]+","+list.get(i).getRow()[3]+","+
                        list.get(i).getCol()[3]+","+list.get(i).getFood()[3]);
                // line feed
                writeText.newLine();
            }
            writeText.flush();
            writeText.close();
        }catch (FileNotFoundException e){
            System.out.println("没有找到指定文件");
        }catch (IOException e){
            System.out.println("文件读写出错");
        }
        return "success!";
    }

    /*
     This method is created to store the passenger whether choose optional service
     @ param bookNumber
     @ param type, the service type
     @ return String, show whether succeed
   */
    public String chooseService(String bookNumber){
        ArrayList<Passenger> list = this.queryAll();

        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getBookNumber().equals(bookNumber)){
                list.get(i).setIsVIP("yes");
                System.out.println(list.get(i));
            }
        }
        File writeFile = new File("src/data/data.csv");
        try{
            BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile));
            for (int i = 0; i < list.size(); i++) {
                // write bytes to stream
                writeText.write(list.get(i).getBookNumber()+","+list.get(i).getSurname()+","+list.get(i).getID()+
                        ","+list.get(i).getIsVIP()+","+list.get(i).getBaggage()+","+list.get(i).getStatus()+","+list.get(i).getPlaneNum()[0]+","+list.get(i).getRow()[0]+","+
                        list.get(i).getCol()[0]+","+list.get(i).getFood()[0]+","+list.get(i).getPlaneNum()[1]+","+
                        list.get(i).getRow()[1]+","+list.get(i).getCol()[1]+","+list.get(i).getFood()[1]+","+
                        list.get(i).getPlaneNum()[2]+","+list.get(i).getRow()[2]+","+list.get(i).getCol()[2]+","+
                        list.get(i).getFood()[2]+","+list.get(i).getPlaneNum()[3]+","+list.get(i).getRow()[3]+","+
                        list.get(i).getCol()[3]+","+list.get(i).getFood()[3]);
                // line feed
                writeText.newLine();
            }
            writeText.flush();
            writeText.close();
        }catch (FileNotFoundException e){
            System.out.println("没有找到指定文件");
        }catch (IOException e){
            System.out.println("文件读写出错");
        }
        return "success!";
    }

    public ArrayList<String> queryPlanePassenger(String currentPlane){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/data/planeData.csv"), "utf-8"));//GBK
            String line = null;
            while((line=reader.readLine())!=null){
                String[] item;
                item = line.split(",");
                String number = item[0];
                if(number.equals(currentPlane)){
                    return new ArrayList<>(Arrays.asList(item).subList(9, item.length));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    /*
       This method is created to query which seats have been taken
       @ return int[][], show which seats have been taken
    */
    public int[][] siteCondition(Passenger passenger){
        String currentPlane = passenger.getCurrentPlaneNum();
        ArrayList<Passenger> passengerList = this.queryAll();
        ArrayList<String> list = queryPlanePassenger(currentPlane);
        int[][] site = new int[29][11];
        HashSet<String> set = new HashSet<>(list);

        for (Passenger value : passengerList) {
            if (set.contains(value.getSurname())) {
                String[] planeNum = value.getPlaneNum();
                int j = 0;
                while (j < planeNum.length) {
                    if (planeNum[j].equals(currentPlane)) {
                        break;
                    }
                    j++;
                }
                int row = Integer.parseInt(value.getRow()[j]);
                int col = Integer.parseInt(value.getCol()[j]);
                site[row][col] = 1;
            }
        }
        return site;
    }

    public Boolean checkBookNumber(String bookNumber){
        boolean result = true;
        String regex = "^1[0-9]{10}$";
        if (!bookNumber.matches(regex)){
            result = false;
        }
        return result;
    }

    public Boolean checkIDNumber(String IDNumber){
        boolean result = true;
        String regex = "^[1-9]\\d{5}(18|19|20|(3\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
        if (!IDNumber.matches(regex)){
            result = false;
        }
        return result;
    }
}
